import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { ListView, Toast } from 'antd-mobile';
import AlbumItem from '../components/AlbumItem'
import { searchAlbum, getUuid, convetAlbums, isContrainAlbum } from '../utils';
import { CACHE_TMP_SEARCH_SCROLL_Y } from '../config';

/**
 * 搜索的专辑列表
 */
class AlbumListBySearch extends Component {
  constructor(props) {
    super(props);

    const ds = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    })
    this.getAlbum = this.getAlbum.bind(this);
    this.onScroll = this.onScroll.bind(this);
    this.state = {
      albumList: this.props.album_list,
      dataSource: ds.cloneWithRows(this.props.album_list),
      height: document.documentElement.clientHeight * 3, // 高度
      isLoading: true,
      hasMore: true,
      keywords: this.props.keywords,
      page: 2,
    }
    this.filterAlbums = [];
  }

  getFilterAlbum() {
    const filterAlbumString = localStorage.getItem('filter_album');
    if (filterAlbumString) {
      this.filterAlbums = JSON.parse(filterAlbumString);
    }
  }


  componentDidMount() {
    let hei = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop
    this.setState({
      height: hei,
    });
    this.checkAlbums = setInterval(() => {
      if (this.filterAlbums.length === 0) {
        this.getFilterAlbum();
      }
    }, 2000);

    const scollY = sessionStorage.getItem(CACHE_TMP_SEARCH_SCROLL_Y);
    if (scollY) {
      setTimeout(() => {
        this.lv.scrollTo(0, parseInt(scollY, 10));
      }, 200);
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      albumList: nextProps.album_list,
      keywords: nextProps.keywords,
      dataSource: this.state.dataSource.cloneWithRows(nextProps.album_list),
    });
  }

  // 滑动位置
  onScroll(event) {
    this.offset = event.target.scrollTop;
    sessionStorage.setItem(CACHE_TMP_SEARCH_SCROLL_Y, this.offset);
  }


  fetch() {
    searchAlbum(getUuid(), this.state.keywords, this.state.page, (function (result) {
      if (result.errcode === 0) {
        let albumList = convetAlbums(result.data)
        let hasMore = (albumList.length === 20);
        let nowAlbumList = this.state.albumList.concat(albumList)
        let page = this.state.page + 1
        this.setState({
          albumList: nowAlbumList,
          dataSource: this.state.dataSource.cloneWithRows(nowAlbumList),
          hasMore: hasMore,
          isLoading: false,
          page: page
        });

      } else {
        this.setState({ isLoading: false, page: 2 });
      }
    }).bind(this))
  }


  handleItemAlbum(album) {
    let flag = isContrainAlbum(this.filterAlbums, album);
    if (flag) {
      const albumList = this.state.albumList;
      this.props.handleItemAlbum({ album: album, album_list: albumList });
    } else {
      Toast.show('该专辑尚未购买', 1, false);
    }

  }

  getAlbum(album, index) {
    return (
      <AlbumItem key={index} album={album} albumItemClick={this.handleItemAlbum.bind(this, album)} />
    )
  }

  onEndReached = (event) => {
    if (this.state.isLoading && !this.state.hasMore) {
      return
    }
    this.setState({ isLoading: true })
    this.fetch()
  }

  componentWillUnmount() {
    clearInterval(this.checkAlbums);
  }


  render() {
    const row = (rowData, sectionID, rowID) => {
      return (
        <div key={rowID} >
          {this.getAlbum(rowData, rowID)}
        </div>
      );
    };

    return (

      <ListView
        ref={el => this.lv = el}
        dataSource={this.state.dataSource}
        renderFooter={() => (
          <div style={{
            padding: 16,
            textAlign: 'center',
            fontSize: '13px',
          }}>
            {this.state.hasMore === true ? "正在加载内容..." : '没有更多内容了~'}
          </div>)}
        renderRow={row}
        style={{
          height: this.state.height,
          overflow: 'auto',
        }}
        initialListSize={2000}
        pageSize={20}
        className="am-list"
        onScroll={this.onScroll}
        scrollEventThrottle={100}
        scrollRenderAheadDistance={300}
        onEndReached={this.onEndReached}
        onEndReachedThreshold={20}
      />

    );
  }
};
export default AlbumListBySearch;
